/**
 * Created by Administrator on 2017/2/23.
 */
import {Component, ViewContainerRef, ViewChild, Input, Output, EventEmitter} from '@angular/core';
import {CommonService} from "../common.service";
declare var $: any;

@Component({
    moduleId: module.id,
    selector: 'associativeInput-component',
    templateUrl: "./associativeInput.html"
})
export class AssociativeInputComponent {
    inputData: any
    @ViewChild("selectDiv") selectDiv: any
    originData: any[] = []

    @Output() getResult = new EventEmitter<string>();

    @Input()
    set associativeOriginData(data: any) {
        this.originData = data
    }
    @Input()
    set initData(data: any) {
        this.inputData = data
    }

    showData: any[] = []

    constructor(private commonService: CommonService) {

    }

    ngOnInit() {

    }

    keyUp(e:any) {
        if (e.key == "Enter") {
            $(this.selectDiv.nativeElement).hide()
        } else {

            this.refreshShowData()
        }
        this.saveData()
    }

    refreshShowData() {
        this.showData = []
        for (let data of this.originData) {
            if (data.indexOf(this.inputData) > -1) {
                this.showData.push(data)
            }
        }
        $(this.selectDiv.nativeElement).show()
    }


    loseFocus() {
        let intervalId = setTimeout(() => {
            $(this.selectDiv.nativeElement).hide()
        }, 300);

        //
    }

    getFocus() {
        if (!this.commonService.emptyStr(this.inputData)) {
            this.refreshShowData()
            $(this.selectDiv.nativeElement).show()
        }

    }


    mouseEnter(e:any) {
        $(e.target).css("background-color", "#f2f2f2")
    }

    mouseLeave(e:any) {
        $(e.target).css("background-color", "transparent")
    }

    selectData(data:any) {
        this.inputData = data
        $(this.selectDiv.nativeElement).hide()
        this.saveData()
    }

    saveData() {
        this.getResult.emit(this.inputData);
    }
}